#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 crane <crane@crane-pc>
#
# Distributed under terms of the MIT license.

"""

"""

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

    def show(self):
        self._rec_show(self)
        print('\n===================  =====================')

    def _rec_show(self, node):
        if not node:
            return

        if node.left:
            self._rec_show(node.left)
            # print(node.val)

        print('%s' % node.val, end=' ', sep=' ')

        if node.right:
            self._rec_show(node.right)



def build_tree_from_str(str_tree):
    # '1,2,3,4,5'       # 1->2, 1->3, 2->4, 2->5
    # '1,2,#,#,#'       # 1->2, 1->#, 2->#, 2->#
    DELIMIT = ","
    results = str_tree.split(DELIMIT)

    # 注意输入的root可能为空
    # root = TreeNode(results.pop(0))
    root = _get_node(results.pop(0))
    if not root:
        return root

    tree_queue = [root]
    # "5,4,6,#,#,#,#"

    while results:
        node = tree_queue.pop(0)

        vl = results.pop(0)
        vr = results.pop(0)

        node.left  = _get_node(vl)
        node.right = _get_node(vr)
        if node.left:
            tree_queue.append(node.left)

        if node.right:
            tree_queue.append(node.right)

    return root

def _get_node(value):
    if value == '#':
        return None

    return TreeNode(int(value))


def main():
    root = build_tree_from_str('1,2,3,4,5')
    root.show()

if __name__ == "__main__":
    main()
